﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Rendering;

/// <summary>
/// UI排序使用
/// 根据当前节点及其父节点最近的Canvas上的排序 重新计算子节点相关组件的排序值
/// Renderer组件排序 SortingGroup组件排序 Canvas组件排序
/// </summary>
public class UIOrder : MonoBehaviour
{
    /// <summary>
    /// 相对哪个canvas的sortingOrder进行排序
    /// </summary>
    private Canvas m_canvas;
    /// <summary>
    /// 重新排序的Renderer对象
    /// </summary>
    private Renderer[] m_renderer;
    /// <summary>
    /// 重新排序的SortingGroup对象
    /// </summary>
    private SortingGroup[] m_sortingGroup;
    /// <summary>
    /// 重新排序的Canvas对象
    /// </summary>
    private Canvas m_sortingCanvas;
    

    /// <summary>
    /// 对Renderer对象进行排序
    /// </summary>
    public bool m_useRenderSorting;
    /// <summary>
    /// 对SortingGroup对象进行排序
    /// </summary>
    public bool m_useSortingGroup;
    /// <summary>
    /// 对Canvas对象进行排序
    /// </summary>
    public bool m_useCanvasSorting;
    void Start()
    {
        //如果对自己的Canvas进行排序 那么排序的基准值采用父对象中的Canvas中的排序值
        m_canvas = m_useCanvasSorting ? transform.parent.GetComponentInParent<Canvas>() : GetComponentInParent<Canvas>();

        //对Renderer对象进行排序
        if (m_useRenderSorting)
        {
            m_renderer = GetComponentsInChildren<Renderer>(true);
            foreach (var render in m_renderer)
            {
                render.sortingOrder += m_canvas.sortingOrder;
            }
        }
        //对SortingGroup对象进行排序
        if (m_useSortingGroup)
        {
            m_sortingGroup = GetComponentsInChildren<SortingGroup>(true);
            foreach (var sortingGroup in m_sortingGroup)
            {
                sortingGroup.sortingOrder += m_canvas.sortingOrder;
            }
        }
        //对Canvas对象进行排序
        if (m_useCanvasSorting)
        {
            m_sortingCanvas = GetComponent<Canvas>();
            m_sortingCanvas.sortingOrder += m_canvas.sortingOrder;
        }
    }
}
